import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { PersistenceOptions } from 'pinia-plugin-persistedstate'

export type PPTHistoryItem = {
  id: string
  taskId: string
  title: string
  description: string
  mode: 'text' | 'file'
  fileName?: string
  pageCount?: number
  previewUrl: string
  downloadUrl?: string
  status: number
  timestamp: number
}

export const usePPTStore = defineStore(
  'ppt',
  () => {
    const history = ref<PPTHistoryItem[]>([])
    const isGenerating = ref(false)
    const currentTaskId = ref('')
    const currentPPTData = ref<any>(null)

    const addToHistory = (item: Omit<PPTHistoryItem, 'id' | 'timestamp'>) => {
      const newItem: PPTHistoryItem = {
        id: Date.now().toString(),
        timestamp: Date.now(),
        ...item
      }
      
      history.value.unshift(newItem)
      
      // 保持历史记录最多30条
      if (history.value.length > 30) {
        history.value = history.value.slice(0, 30)
      }
    }

    const updateHistoryItem = (taskId: string, updates: Partial<PPTHistoryItem>) => {
      const index = history.value.findIndex(item => item.taskId === taskId)
      if (index !== -1) {
        history.value[index] = { ...history.value[index], ...updates }
      }
    }

    const removeHistoryItem = (id: string) => {
      const index = history.value.findIndex(item => item.id === id)
      if (index !== -1) {
        history.value.splice(index, 1)
      }
    }

    const clearHistory = () => {
      history.value = []
    }

    const setGenerating = (generating: boolean) => {
      isGenerating.value = generating
    }

    const setCurrentTaskId = (taskId: string) => {
      currentTaskId.value = taskId
    }

    const setCurrentPPTData = (data: any) => {
      currentPPTData.value = data
    }

    return {
      history,
      isGenerating,
      currentTaskId,
      currentPPTData,
      addToHistory,
      updateHistoryItem,
      removeHistoryItem,
      clearHistory,
      setGenerating,
      setCurrentTaskId,
      setCurrentPPTData
    }
  },
  {
    persist: {
      key: 'ppt-store',
      storage: localStorage,
      paths: ['history']
    } as PersistenceOptions
  }
) 